<?php
/*
 * @Description: 售后处理
 * @Author: QinTianyu
 * @Date: 2020-04-24 11:18:02
 * @LastEditors: QinTianyu
 * @LastEditTime: 2020-05-09 17:03:54
 */
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\Course as CourseModel;
use app\finance\model\Account as AccountModel;
use app\user\model\User as UserModel;
use app\system\model\systemUser as systemUserModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\product\model\Project as ProjectModel;
use app\product\model\Product as ProductModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCardDetailLog as UserCardDetailLogModel;
use think\Db;
use app\warehouse\model\Stock as StockModel;
use app\warehouse\model\Warehouse as WarehouseModel;
class Aftermarket extends Admin
{
	public function initialize()
    {
		parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);

        // $this->assign('admin_type',$admin['type']);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where['shop_id'] = session('shop_id');
            // 会员
            $userArr = UserModel::all();
            $users = UserModel::getSelect($userArr);
            $this->assign('users', $users);
            $this->assign('userArr', $userArr);

			$account_arr = AccountModel::where('status',1)->where('id','<>',0)->all();
			$account_arr[] = ['id'=> -3,'name'=>'赠送'];
			$account_arr[] = ['id' => -5, 'name' => "会员卡赠送"];
			// 7-1 修改 退会员卡增加退会员卡赠送
            $accounts = AccountModel::getSelect($account_arr);


            $this->assign('accounts', $accounts);
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            $cashiers = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }else if($value['type'] == '前台'){
                	$cashiers[] = $value;
                }
            }
            // halt();
            $this->assign('cashiers', $cashiers);
            $this->assign('adviserArr', $advisers);
            $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('technicians', systemUserModel::where('type', 7)->where('shop_id',session('shop_id'))->field('id as value,nick as name')->all());

        }
    }
	/**
	 * [refund 退疗程卡]
	 * @return [type] [description]
	 */
	public function refund()
	{
		if($this->request->isAjax()){
			$where = [];
			$page = $this->request->param('page');
			$limit = $this->request->param('limit');

			$user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
			$data['data'] = Db::name('aftermarket_liao')
			->where('shop_id',session('shop_id'))
			->where($where)
			->whereTime('createtime', [strtotime($start), strtotime($end ."+1 day")])
			->page($page)
            ->limit($limit)
			->order('id desc')->select();
			$account_arr = Db::name('account')->where('status',1)->column('id,name');
			$account_arr[-2] = '会员卡赠送';
			$account_arr[-3] = '赠送';

			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['account_name'] = $account_arr[$value['account_id']];
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['count'] = Db::name('aftermarket_liao')->where('shop_id',session('shop_id'))->count('id');
			$data['code'] = 0;
			return json($data);
		}
		return $this->fetch();
	}
	public function dayinRefund()
	{
		$id = $this->request->param('id');
		$formData = Db::name("aftermarket_liao")->where('id',$id)->find();
		$formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
		$formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
		$formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
		$formData['cashier_name'] = Db::name('system_user')->where('id',$formData['cashier_id'])->value('nick');
		$formData['technician_name'] = implode(',',Db::name('system_user')->where('id','in',$formData['technician_ids'])->column('nick'));
		$account_arr = Db::name('account')->where('status',1)->column('id,name');
		$account_arr[-2] = '会员卡赠送';
		$account_arr[-3] = '赠送';

		$formData['account_name'] = $account_arr[$formData['account_id']];
		// halt($formData);
		$this->assign('formData',$formData);
		$data = json_decode($formData['multiple'],true);
		// halt($data);
		$newData = array_more_group($data,['cardname','name']);

		$xxx = [];
		foreach ($newData as $key => $value) {
			$k = explode('_',$key);
			$xxx[] = [
				'cardname' => $k[0],
				'name' => $k[1],
				'count' => count($value),
			];
		}
		$this->assign('lists',$xxx);
		$this->view->engine->layout(false);
		return $this->fetch();
	}
	public function lookRefund()
	{
		$id = $this->request->param('id');
		$lists = Db::name("aftermarket_liao")->where('id',$id)->value('multiple');
		$this->assign('lists',json_decode($lists,true));
		// halt(json_decode($lists,true));
		return $this->fetch();
	}


	/**
	 * [addRefund 新增退款]
	 */
	public function addRefund()
	{
		if($this->request->isPost()){
			$postData = $this->request->post();
			if($postData['price'] <0){
				return $this->axiosMsg('退款金额不能为负数', false);
			}
			if(!isset($postData['account_id'])){
            	return $this->axiosMsg('支出账户不能为空！');
			}
			// halt($postData);
			if(empty($postData['multipleSelection'])){
            	return $this->axiosMsg('疗程卡不能为空！');
			}
			if(empty($postData['account_id']) && $postData['account_id'] != 0){
					return $this->axiosMsg('支出账户不能为空！');
			}
			$postData['sn'] = create_order_sn();
			// 退卡单
			$postData['createtime'] = time();
			$postData['shop_id'] = session('shop_id');
			// $multipleSelection = $postData['multipleSelection'];

			$postData['technician_ids'] = implode(',',$postData['technician_ids']);
			$postData['multiple'] = json_encode($postData['multipleSelection']);
			unset($postData['multipleSelection']);

			if(Db::name('aftermarket_liao')->insert($postData)){
				return $this->axiosMsg('退款成功',true);
			}
			return $this->axiosMsg('出现未知错误，请联系管理员',false);

		}
		$account_arr = AccountModel::where('status',1)->field('id,name')->all();

		$account_arr[] = ['id'=> -2,'name'=>'会员卡赠送'];
		$account_arr[] = ['id'=> -3,'name'=>'赠送'];
        $this->assign('accountArr', $account_arr);
		return $this->fetch();
	}

	/**
	 * [getProject 获取用户购买过的疗程卡]
	 * @return [type] [description]
	 */
	public function getProject()
	{
		$id = $this->request->param('id');
		$cards = Db::name('user_card')->alias('u')
		->join('course c','u.course_id=c.id')
		->field('u.*,c.name')
		->where('u.user_id',$id)
		->select();
		$cardsArr = [];
		$ci = Db::name('user_card_log')->where('user_id',$id)->where('use',1)->select();
		$account_arr = AccountModel::where('status',1)->column('id,name');
		$account_arr[-5] = '会员卡赠送';
		$account_arr[-2] = '赠送';
		foreach ($cards as $key => $value) {
			foreach ($ci as $k => $v) {
				if($value['sn'] == $v['sn']){
					$v['cardname'] = $value['name'];
					$v['account'] = $account_arr[$value['account_id']];
					$v['cardprice'] = $value['price1'];
					if($v['type'] == 1){   //  项目
						$v['name'] = Db::name('project')->where('id',$v['pid'])->value('name');
					}else{
						$v['name'] = Db::name('product')->where('id',$v['pid'])->value('name');
					}
					$cardsArr[] = $v;
				}
			}
		}

		return json($cardsArr);
	}
	/**
	 * [card 退卡]
	 * @return [type] [description]
	 */
	public function card()
	{
		if($this->request->isAjax()){

			$where = [];
			$page = $this->request->param('page');
			$limit = $this->request->param('limit');
			$user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
			}


			$data['data'] = Db::name('aftermarket_card')
			->where('shop_id',session('shop_id'))
			->where($where)
			->whereTime('createtime', [strtotime($start), strtotime($end ."+1 day")])
			->page($page)
            ->limit($limit)
			->order('id desc')->select();
			$account_arr = Db::name('account')->where('status',1)->column('id,name');
			$account_arr[-2] = '会员卡赠送';
			$account_arr[-3] = '赠送';
			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['account_name'] = isset($account_arr[$value['account_id']]) ? $account_arr[$value['account_id']] : '--';
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['count'] = Db::name('aftermarket_card')->where('shop_id',session('shop_id'))->count('id');
			$data['code'] = 0;
			return json($data);
		}
		return $this->fetch();
	}

	public function dayinCard()
	{
		$id = $this->request->param('id');
		$formData = Db::name('aftermarket_card')->where('id',$id)->find();
		$formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
		$formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
		$formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
		$formData['cashier_name'] = Db::name('system_user')->where('id',$formData['cashier_id'])->value('nick');
		$formData['technician_name'] = implode(',',Db::name('system_user')->where('id','in',$formData['technician_ids'])->column('nick'));
		$account_arr = Db::name('account')->where('status',1)->column('id,name');
		$account_arr[-2] = '会员卡赠送';
		$account_arr[-3] = '赠送';

		$formData['account_name'] = isset($account_arr[$formData['account_id']]) ? $account_arr[$formData['account_id']] : '--';
		$this->assign('formData',$formData);
		$this->view->engine->layout(false);
		return $this->fetch();
	}
	/**
	 * [addCard 新增退卡]
	 * 7-1 新增 退赠送会员卡， 赠送会员卡 只是消除赠送会员卡账户中的金额
	 */
	public function addCard()
	{
		if($this->request->isPost()){
			$postData = $this->request->post();
			$userModel = new UserModel;
			// 赠送会员卡
			if($postData['type'] == 2){
				if($postData['price'] <= 0){
					return $this->error('退卡金额必须大于0！');
				}
				$userBalanceZeng = $userModel->getUserBalance($postData['user_id'],2);
				if($userBalanceZeng < $postData['price']){
					return $this->error('退卡金额过多！');
				}
				if(!isset($postData['account_id']) || empty($postData['account_id'])){
					return $this->error('支出账户不能为空！');
				}

				if($postData['account_id'] != -3){
					return $this->error('支出账户请选择赠送！');
				}
				Db::startTrans();
				try {
					// 退卡单
					$postData['createtime'] = time();
					Db::name('aftermarket_card')->insert($postData);



					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					return $this->error($e->getMessage());
				}
				return $this->success('退卡成功！');
			}

			$userBalance = $userModel->getUserBalance($postData['user_id'],1);

            if($userBalance < $postData['price']){
            	return $this->error('退卡金额过多！');
			}
			if(!isset($postData['account_id']) || empty($postData['account_id'])){
            	return $this->error('支出账户不能为空！');
            }
            if($postData['price'] <= 0){
            	return $this->error('退卡金额必须大于0！');
            }
            Db::startTrans();

            try {
            	// 退卡单
            	$postData['createtime'] = time();
            	Db::name('aftermarket_card')->insert($postData);
            	Db::commit();
            } catch (Exception $e) {
            	Db::rollback();
            	return $this->error($e->getMessage());
            }
            return $this->success('退卡成功！');
		}
		return $this->fetch();
	}
	/**
	 * [checkCard 审核退卡]
	 * @return [type] [description]
	 */
	public function checkCard()
	{
		$id = $this->request->param('id');
		$formData = Db::name('aftermarket_card')->where('id',$id)->find();
		if(!$formData){
			return $this->error('订单不存在');
		}
		if($this->request->isPost()){
			$userModel = new UserModel;
			$postData = $this->request->post();
			// halt($postData);

			$data = [];
			$postData['finance_id'] = ADMIN_ID;
			if($postData['type'] == 2){  // 赠送会员卡

				if($postData['price'] <= 0){
					return $this->error('退卡金额必须大于0！');
				}
				$userBalanceZeng = $userModel->getUserBalance($postData['user_id'],2);
				if($userBalanceZeng < $postData['price']){
					return $this->error('退卡金额过多！');
				}
				if(!isset($postData['account_id']) || empty($postData['account_id'])){
					return $this->error('支出账户不能为空！');
				}

				if($postData['account_id'] != -3){
					return $this->error('支出账户请选择赠送！');
				}
				Db::startTrans();
				try {
					Db::name('aftermarket_card')->where('id',$id)->update($postData);
					if($postData['status'] == 2){
						// 扣除会员卡
						$balanceData = [
							'user_id' => $postData['user_id'],
							'type' => 5,
							'price' => $postData['price'],
							'sn' => $formData['sn'],
							'createtime' => time(),
							'is_give' => 2,
							'updatetime' => time()
						];
						Db::name('user_balance_log')->insert($balanceData);
					}
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					return $this->error($e->getMessage());
				}
				return $this->success('退卡成功！');
			}
			$userBalance = $userModel->getUserBalance($postData['user_id'],1);

            if($userBalance < $postData['price']){
            	return $this->error('退卡金额过多！');
			}
			if(!isset($postData['account_id']) || empty($postData['account_id'])){
            	return $this->error('支出账户不能为空！');
            }
            if($postData['price'] <= 0){
            	return $this->error('退卡金额必须大于0！');
            }
			Db::startTrans();
			try {

				Db::name('aftermarket_card')->where('id',$id)->update($postData);
				if($postData['status'] == 2){
					// 银行卡支出
					$sys = [
						'sn' => $formData['sn'],
						'account_id' => $postData['account_id'],
						'shop_id' => $formData['shop_id'],
						'type' => 9,
						'price' => $postData['price'],
						'is_effective' => 1,
						'cate' => 2,
						'user_id' => $postData['user_id'],
						'createtime' => time(),
						'updatetime' => time(),
					];
					Db::name('system_balance_log')->insert($sys);


					// 绩效********************************************************
					$meirongshi = Db::name('system_user')->where('id','in',$postData['technician_ids'])->column('id,nick');
					$jixiao = [];
					// dump($value );
					$jixiao[] = [
						'admin_id' => $postData['adviser_id'],
						'user_id' => $postData['user_id'],
						'project' => '会员退卡',
						'num' => 1,
						'price' => $postData['price'],
						'shougong' => 0,
						'settlement' => '销售退回',
						'shop_id' => $formData['shop_id'],
						'admin_type' => '顾问',
						'proportion' => 0,
						'createtime' => date('Y-m-d H:i:s',time()),
						'sn' => $formData['sn'],
					];
					foreach ($meirongshi as $k => $v) {
						$jixiao[] = [
							'admin_id' => $k,
							'user_id' => $postData['user_id'],
							'project' => '会员退卡',
							'num' => 1,
							// 'price' => $postData['price'],
							'price' => round(($postData['price'] / count($meirongshi)),2),
							'shougong' => 0,
							'settlement' => '销售退回',
							'shop_id' => $formData['shop_id'],
							'admin_type' => '美容师',
							'proportion' => 0,
							'createtime' => date('Y-m-d H:i:s',time()),
							'sn' => $formData['sn'],
						];
					}
					if(count($jixiao) > 0){
						Db::name('achievements')->insertAll($jixiao);
					}
					// 绩效********************************************************
					// 扣除会员卡
					$balanceData = [
						'user_id' => $postData['user_id'],
						'type' => 5,
						'price' => $postData['price'],
						'sn' => $formData['sn'],
						'createtime' => time(),
						'is_give' => 1,
						'updatetime' => time()
					];
					Db::name('user_balance_log')->insert($balanceData);
				}

				Db::commit();
            } catch (Exception $e) {
            	Db::rollback();
            	return $this->error($e->getMessage());
            }
			// if(){
				return $this->success('审核完成');
			// }
			// return $this->error('出现未知错误');
			// halt($postData);
		}
		$formData['technician_ids'] = Db::name('system_user')->where('id','in',$formData['technician_ids'])->field('id as value, nick as name')->select();

		$this->assign('formData', $formData);
		// $this->assign('financ', $financ);
		return $this->fetch();
	}


	public function product()
	{
		if($this->request->isAjax()){

			$page = $this->request->param('page');
			$limit = $this->request->param('limit');
			$where = [];
			$user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
			}
			$data['data'] = Db::name('aftermarket_product')->where($where)->where('createtime','between',[strtotime($start),strtotime($end ."+1 day")])->page($page)->limit($limit)->order('id desc')->select();
			$data['count'] = Db::name('aftermarket_product')->where($where)->where('createtime','between',[strtotime($start),strtotime($end ."+1 day")])->page($page)->limit($limit)->order('id desc')->count('id');
			$account_arr = Db::name('account')->where('status',1)->column('id,name');
			$account_arr[-2] = '会员卡赠送';
			$account_arr[-3] = '赠送';
			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['account_name'] = $account_arr[$value['account_id']];
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['code'] = 0;
			return json($data);
		}
		return $this->fetch();
	}

	public function dayinProduct()
	{
		$id = $this->request->param('id');
		$formData = Db::name('aftermarket_product')->where('id',$id)->find();
		$formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
		$formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
		$formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
		$formData['cashier_name'] = Db::name('system_user')->where('id',$formData['cashier_id'])->value('nick');
		$formData['technician_name'] = implode(',',Db::name('system_user')->where('id','in',$formData['technician_ids'])->column('nick'));
		$account_arr = Db::name('account')->where('status',1)->column('id,name');
		$account_arr[-2] = '会员卡赠送';
		$account_arr[-3] = '赠送';
		$formData['account_name'] = isset($account_arr[$formData['account_id']]) ? $account_arr[$formData['account_id']] : '--';
		$this->assign('formData',$formData);
		$lists = json_decode($formData['products'],true);
		$this->assign('lists', $lists);
		// halt($lists);
		$this->view->engine->layout(false);
		return $this->fetch();
	}
	/**
	 * [addProduct 添加退产品单]
	 */
	public function addProduct()
	{
		if($this->request->isPost()){
			$postData = $this->request->post();
			$sn = create_order_sn();
			if(!isset($postData['account_id']) || (empty($postData['account_id']) && $postData['account_id'] != 0)){
            	return $this->axiosMsg('支出账户不能为空！',false);
			}
			// 退产品单
			$postData['createtime'] = time();
			$productArr = $postData['productData'];
			if(empty($postData['productData']) || !isset($postData['productData'])){
				return $this->axiosMsg("产品不能为空", false);
			}

			// 退单表
			$postData['products'] = json_encode($productArr);
			$postData['sn'] = $sn;
			$postData['technician_ids'] = implode(',',$postData['technician_ids']);
			$postData['shop_id'] = session('shop_id');
			unset($postData['productData']);

			try {
				Db::name('aftermarket_product')->insert($postData);
			} catch (\Exception $e) {
				return $this->axiosMsg('退款失败',false);
			}
			return $this->axiosMsg('退款成功！', true);

		}
		$account_arr = AccountModel::where('status',1)->field('id,name')->all();

		$account_arr[] = ['id'=> -2,'name'=>'会员卡赠送'];
		$account_arr[] = ['id'=> -3,'name'=>'赠送'];
        $this->assign('accountArr', $account_arr);
		$products = Db::name('product')->where('status',1)->field('id,name,price2')->all();
		$this->assign('products', $products);
		$warehouses = Db::name('warehouse')->field('id,name')->select();
		$this->assign('warehouses',$warehouses);
		return $this->fetch();
	}


	public function lookProduct()
	{
		$id = $this->request->param('id');
		$productArr = Db::name('aftermarket_product')->where('id',$id)->value('products');
		if(!$productArr){
			return $this->error('订单不存在或没有权限');
		}
		$this->assign('productArr', json_decode($productArr,true));
		return $this->fetch();
	}
	/**
	 * 退疗程卡审核
	 */
	public function checkRefund()
	{
		$id = $this->request->param('id');
		if($this->request->isPost()){
			$postData = $this->request->post();
			Db::startTrans();
			try {
				Db::name("aftermarket_liao")->where('id',$id)->update(['status'=>$postData['status']]);
				if($postData['status'] == 2){
					$data = Db::name("aftermarket_liao")->where('id',$id)->find();
					$multipleSelection = json_decode($data['multiple'],true);

					if($data['account_id'] == 0){
						$balanceData = [
							'user_id' => $data['user_id'],
							'type' => 1,
							'price' => $data['price'],
							'sn' => $data['sn'],
							'createtime' => time(),
							'is_give' => 1,
							'updatetime' => time()
						];
						Db::name('user_balance_log')->insert($balanceData);
					}else if($data['account_id'] == -2){
						$balanceData = [
							'user_id' => $data['user_id'],
							'type' => 1,
							'price' => $data['price'],
							'sn' => $data['sn'],
							'createtime' => time(),
							'is_give' => 2,
							'updatetime' => time()
						];
						Db::name('user_balance_log')->insert($balanceData);
					}else if($data['account_id'] == -3){

					}else{
						$sys = [
							'sn' => $data['sn'],
							'account_id' => $data['account_id'],
							'shop_id' => $data['shop_id'],
							'type' => 10,
							'price' => $data['price'],
							'is_effective' => 1,
							'cate' => 2,
							'user_id' => $data['user_id'],
							'createtime' => time(),
							'updatetime' => time(),
						];
						Db::name('system_balance_log')->insert($sys);
					}

					$fangshi = '销售退回';
					if($data['account_id'] == -3){
						$fangshi = '赠送退回';
					}

					// 绩效********************************************************
					$meirongshi = Db::name('system_user')->where('id','in',$data['technician_ids'])->column('id,nick');
					$jixiao = [];
					// dump($value );
					$jixiao[] = [
						'admin_id' => $data['adviser_id'],
						'user_id' => $data['user_id'],
						'project' => '会员退款',
						'num' => 1,
						'price' => $data['price'],
						'shougong' => 0,
						'settlement' => $fangshi,
						'shop_id' => $data['shop_id'],
						'admin_type' => '顾问',
						'proportion' => 0,
						'createtime' => date('Y-m-d H:i:s',time()),
						'sn' => $data['sn'],
					];
					// halt($data['price']);
					foreach ($meirongshi as $k => $v) {
						$jixiao[] = [
							'admin_id' => $k,
							'user_id' => $data['user_id'],
							'project' => '会员退款',
							'num' => 1,
							// 'price' => $data['price'],
							'price' => round(($data['price'] / count($meirongshi)),2),
							'shougong' => 0,
							'settlement' => $fangshi,
							'shop_id' => $data['shop_id'],
							'admin_type' => '美容师',
							'proportion' => 0,
							'createtime' => date('Y-m-d H:i:s',time()),
							'sn' => $data['sn'],
						];
					}
					if(count($jixiao) > 0){
						Db::name('achievements')->insertAll($jixiao);
					}
					// 绩效********************************************************
					// 扣除疗程卡
					$idsArr = [];
					$updateArr = [];
					$detailLog = [];
					$use_num = [];
					foreach ($multipleSelection as $key => $value) {
						if($value['type'] == 1){
							$idsArr[$value['pid']][] = 1;
							$start_num = UserCardLogModel::where('sn',$value['sn'])->where('pid',$value['pid'])->where('use',1)->count('id');
							// $start_num = UserCardLogModel::getUserCards($data['user_id'], $value['pid']);
							$price = ProjectModel::getProjectPrice($value['pid']);
							// $price = $data['price'] / count($multipleSelection);
								// halt($price);
							$course_id = Db::name('user_card')->where('sn',$value['sn'])->value('course_id');
							$use_num[$course_id.'_'.$value['pid'].'_'.$start_num.'_'.$price][] = 1;
						}

						$updateArr[] = $value['id'];

					}

					foreach ($use_num as $key => $value) {
							$newArr = explode('_',$key);
							$detailLog[] = [
								'userid'    => $data['user_id'],
								'course_id' => $newArr[0],
								'cid'       => $newArr[1],
								'price'     => $newArr[3] * array_sum($value),
								'start_num' => $newArr[2],
								'use_num'   => array_sum($value),
								'end_num'   => $newArr[2] - array_sum($value),
								'type'      => 3,
								'createtime'=> time()
							];

					}
					UserCardDetailLogModel::insertAll($detailLog);
					Db::name('user_card_log')->where('id','in',$updateArr)->update(['use'=>3,'updatetime'=>time()]);

				}
				Db::commit();
			} catch (\Exception $e) {
				Db::rollback();
				return $this->axiosMsg($e->getMessage(),false);
			}

			return $this->axiosMsg('审核完成',true);






		}
		$formData = Db::name("aftermarket_liao")->where('id',$id)->find();
		$formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
		$formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
		$formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
		$formData['cashier_name'] = Db::name('system_user')->where('id',$formData['cashier_id'])->value('nick');
		$formData['technician_name'] = implode(',',Db::name('system_user')->where('id','in',$formData['technician_ids'])->column('nick'));
		$account_arr = Db::name('account')->where('status',1)->column('id,name');
		$account_arr[-2] = '会员卡赠送';
		$account_arr[-3] = '赠送';

		$formData['account_name'] = $account_arr[$formData['account_id']];

		$this->assign('formData',$formData);
		$data = json_decode($formData['multiple'],true);
		// halt($formData);
		$newData = array_more_group($data,['cardname','name']);

		$xxx = [];
		if($newData){
			foreach ($newData as $key => $value) {
				$k = explode('_',$key);
				$xxx[] = [
					'cardname' => $k[0],
					'name' => $k[1],
					'count' => count($value),
				];
			}
		}

		$this->assign('lists',$xxx);
		return $this->fetch();
	}
	/**
	 * @description:
 	 * @param {type}
	 * @return:
	 * @author: QinTianyu
	 */
	public function checkProduct()
	{
		$id = $this->request->param('id');
		if($this->request->isPost()){
			$post = $this->request->post();

			if($post['status'] == 2){
				Db::startTrans();
				try {
					$postData = Db::name('aftermarket_product')->where('id',$post['id'])->find();

					$sn = $postData['sn'];
					// 退产品单
					$postData['createtime'] = time();
					$productArr = json_decode($postData['products'],true);
					if(empty($productArr) || !isset($productArr)){
						throw new \Exception("产品不能为空", 1);
					}

					// 退单表
					Db::name('aftermarket_product')->where('id',$id)->update(['status'=>$post['status']]);
					// 判断是退现金还是退到会员卡
					if($postData['account_id'] == 0){
						$balanceData = [
							'user_id' => $postData['user_id'],
							'type' => 1,
							'price' => $postData['price'],
							'sn' => $sn,
							'createtime' => time(),
							'is_give' => 1,
							'updatetime' => time()
						];
						Db::name('user_balance_log')->insert($balanceData);
					}else if($postData['account_id'] == -2){
						$balanceData = [
							'user_id' => $postData['user_id'],
							'type' => 1,
							'price' => $postData['price'],
							'sn' => $sn,
							'createtime' => time(),
							'is_give' => 2,
							'updatetime' => time()
						];
						Db::name('user_balance_log')->insert($balanceData);
					}else if($postData['account_id'] == -3){

					}else{
						$sys = [
							'sn' => $postData['sn'],
							'account_id' => $postData['account_id'],
							'shop_id' => $postData['shop_id'],
							'type' => 11,
							'price' => $postData['price'],
							'is_effective' => 1,
							'cate' => 2,
							'user_id' => $postData['user_id'],
							'createtime' => time(),
							'updatetime' => time(),
						];
						Db::name('system_balance_log')->insert($sys);
					}
					$fangshi = '销售退回';
					if($postData['account_id'] == -3){
						$fangshi = '赠送退回';
					}
					// 绩效********************************************************
					$meirongshi = Db::name('system_user')->where('id','in',$postData['technician_ids'])->column('id,nick');
					$jixiao = [];
					$jixiao[] = [
						'admin_id' => $postData['adviser_id'],
						'user_id' => $postData['user_id'],
						'project' => '会员退产品',
						'num' => 1,
						'price' => $postData['price'],
						'shougong' => 0,
						'settlement' => $fangshi,
						'shop_id' => $postData['shop_id'],
						'admin_type' => '顾问',
						'proportion' => 0,
						'createtime' => date('Y-m-d H:i:s',time()),
						'sn' => $postData['sn'],
					];
					foreach ($meirongshi as $k => $v) {
						$jixiao[] = [
							'admin_id' => $k,
							'user_id' => $postData['user_id'],
							'project' => '会员退产品',
							'num' => 1,
							// 'price' => $postData['price'],
							'price' => round(($postData['price'] / count($meirongshi)),2),
							'shougong' => 0,
							'settlement' => $fangshi,
							'shop_id' => $postData['shop_id'],
							'admin_type' => '美容师',
							'proportion' => 0,
							'createtime' => date('Y-m-d H:i:s',time()),
							'sn' => $postData['sn'],
						];
					}
					if(count($jixiao) > 0){
						Db::name('achievements')->insertAll($jixiao);
					}
					// 绩效********************************************************
					if($postData['leixing'] == 1){
						$stock = [];
						$StockModel = new StockModel;
						   foreach ($productArr as $key => $value) {
								$begin_num = $StockModel->getBeginNum($value['warehouse_id'],$value['id']);
								$product_price = $StockModel->getProductPrice($value['warehouse_id'],$value['id']); // 成本价
								$warehouseModel = new WarehouseModel;
								$product_info = ProductModel::get($value['id']);
								if($product_price == 0){
									$warehouse_type = $warehouseModel->warehouseType($value['warehouse_id']);
									if($warehouse_type == 1){  //  配料库
										$product_price = $product_info->price1 / $product_info->specs;
									}else{   //  总库
										$product_price = $product_info->price1;
									}
								}
							   $stock[] = [
								'product_id' => $value['id'],
								'product_num' => $value['num'],
								'product_name' => $value['name'],
								'shop_id' => $postData['shop_id'],
								'sn' => $postData['sn'],
								'type' => '入库',
								'detailed_type' => 8,
								'user_id' => $postData['user_id'],
								'warehouse_id' => $value['warehouse_id'],
								'createtime' => time(),
								'status' => 1,
								'bak' => '销售退回',
								'updatetime' => time(),
								'price'         => $value['price2'],
	                            'unit_price'    => $product_price * $value['num'],
	                            'begin_num'     => $begin_num,
	                            'end_num'       => $begin_num + $value['num']
							   ];
						   }
						Db::name('stock')->insertAll($stock);
					}else{

						$depositInfo = Db::name('deposit')->where('id',$postData['d_id'])->find();
						$deposit = [];
						// 寄存单退货是一个商品
						foreach ($productArr as $key => $value) {
							$depositInfo['specs'] = Db::name('product')->where('id',$depositInfo['product_id'])->value('specs');

					        $depositInfo['num_l'] = Db::name('deposit_log')->where('d_id',$depositInfo['id'])->sum('product_num_l');

					        $depositInfo['num_s'] = $depositInfo['num'] - $depositInfo['num_l'];
							if($depositInfo['num_s'] - $value['num'] == 0){
				                $statusxx = 2;
				            }else{
				                $statusxx = 3;
				            }

							$unit_price = $depositInfo['unit_price'];
							$deposit = [
								'product_id'     => $depositInfo['product_id'],
								'product_num_l'  => $value['num'],
								'product_name'   => $value['name'],
								'd_id'           => $depositInfo['id'],
								'user_name'      =>  Db::name('user')->where('id',$postData['user_id'])->value('nick'),
								'createtime'     => date('Y-m-d H:i:s',time()),
								'user_id'        => $postData['user_id'],
								'product_num_s'  => $depositInfo['num_s'],
								'remark'         => '寄存单退货',
								'ware_id'        => $value['warehouse_id'],
								'unit_price'     =>  $unit_price / $depositInfo['num'] * $value['num'],
								'type'           => 2
							];

						}
						if(!Db::name('deposit_log')->insert($deposit)){
							throw new \Exception("deposit_log Error", 1);

						}
						if(!Db::name('deposit')->where('id',$depositInfo['id'])->update(['status'=>$statusxx])){
							throw new \Exception("deposit Error", 1);

						}


					}

					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					return $this->axiosMsg($e->getMessage(),false);
				}

			}else{
				Db::name('aftermarket_product')->where('id',$id)->update(['status'=>$post['status']]);
			}
			return $this->success('审核完成');
		}
		$formData = Db::name('aftermarket_product')->where('id',$id)->find();
		$formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');

		$formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
		$formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
		$formData['cashier_name'] = Db::name('system_user')->where('id',$formData['cashier_id'])->value('nick');
		$formData['technician_name'] = implode(',',Db::name('system_user')->where('id','in',$formData['technician_ids'])->column('nick'));
		$account_arr = Db::name('account')->where('status',1)->column('id,name');
		$account_arr[-2] = '会员卡赠送';
		$account_arr[-3] = '赠送';
		$formData['account_name'] = isset($account_arr[$formData['account_id']]) ? $account_arr[$formData['account_id']] : '--';
		$this->assign('formData',$formData);
		$lists = json_decode($formData['products'],true);
		foreach ($lists as $key => $value) {
			$lists[$key]['warehouse_name'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
		}
		$this->assign('lists', $lists);
		return $this->fetch();
	}
}
